<template>
  <div>
    <NavHeader class="article-header" />
    <div class="article">
      <input placeholder="请输入标题..." v-model="title" class="article-title" />
      <div>
        <textarea placeholder="说点什么..." v-model="content" class="article-content" />
        <div class="article-pic">
          <div class="upload" v-for="(item, index) in picList" :key="index">
            <span>
              +
            </span>
            <img class="upload-img" :id="`img${index}`" alt="" />
            <input :id="`file${index}`" class="file" type="file" v-on:change="UploadImg(this, index)" />
          </div>
        </div>
      </div>
    </div>
    <el-button @click="handleSubmitArticle">发表</el-button>
  </div>
</template>

<script lang="ts" setup>
import NavHeader from "@/components/header"
import { ref } from "vue"
import { addArticle } from "@/api/article"
import { ElMessage } from "element-plus";
import { userStore } from '@/store/user'
import router from "@/router";
const title = ref('')
const content = ref('')
const user_store = userStore()
let picList: any = ref([""])
const userInfo = user_store.$state.userInfo
const handleSubmitArticle = async () => {
  picList.value.shift()
  const data = {
    u_id: userInfo._id,
    author: userInfo.nickname,
    avatar: userInfo.avatar,
    title: title.value,
    content: content.value,
    pic: picList.value
  }
  if (!title.value || !content.value) {
    return ElMessage('请输入标题或内容')
  }
  const res = await addArticle(data)
  if (res) {
    ElMessage('发布成功')
    router.back()
  }
}
// 图片上传预览
function UploadImg(obj: any, index: any) {
  var reader = new FileReader()
  let file: any = <HTMLInputElement>document.getElementById(`file${index}`)
  let fileUrl = file.files[0]
  reader.readAsDataURL(fileUrl)
  reader.onload = function (e: any) {
    //成功读取文件
    var img = <HTMLImageElement>document.getElementById(`img${index}`)
    img.src = e.target.result
    picList.value.push(e.target.result)
    console.log(picList.value);
  }
}
</script>
<style lang="less" scoped>
.article {
  display: flex;
  flex-direction: column;
  padding: 90px 30px 0 30px;

  &-pic {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }

  &-content {
    display: flex;
    min-height: 500px;
    width: 100%;
    background-color: #f4f3f3f2;
  }
}

.upload {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #dcdfe6;
  min-width: 200px;
  height: 200px;
  color: #222222;

  >span {
    position: absolute;
    font-size: 50px;
  }

  &-img[src=''] {
    opacity: 0;
  }

  &-img {
    // width: 100%;
    height: 100%;
    z-index: 9;
  }
}

.file {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
}

.el-button {
  width: 100px;
}
</style>